import xbmc
import xbmcgui
import xbmcaddon
import os, sys
from xmlParser import XMLParser
import urllib2
import cookielib
import base64

PLUGIN_NAME = 'Intrego Server'


try:
	import json
except ImportError:
	try:
		import simplejson as json
		xbmc.log( '[%s]: Error import json. Uses module simplejson' % PLUGIN_NAME, 2 )
	except ImportError:
		try:
			import demjson3 as json
			xbmc.log( '[%s]: Error import simplejson. Uses module demjson3' % PLUGIN_NAME, 3 )
		except ImportError:
			xbmc.log( '[%s]: Error import demjson3. Sorry.' % PLUGIN_NAME, 4 )


#enable localization
getLS   = sys.modules[ "__main__" ].__language__
__cwd__ = sys.modules[ "__main__" ].__cwd__	
__addon__ = xbmcaddon.Addon( id = 'script.intrego-server' )


def Get(url, ref=None):
        xbmc.output('[%s] Get. Full URL=%s)' % (PLUGIN_NAME, url))
        http = None 
        
        try:        
            cj = cookielib.CookieJar()
            urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)))
        
            request = urllib2.Request(url)
            request.add_header('Accept', 'text/html, application/xml, application/xhtml+xml, */*')
            request.add_header('Accept-Language', 'ru,en;q=0.9')
        
            o = urllib2.urlopen(request)
        
            http = o.read()
            o.close()
            xbmc.log('[%s] Get.RequestInfo. GetURL=%s, Len=%s, Info=%s' % (PLUGIN_NAME, o.geturl(), len(http), o.info()))        
        except:
            xbmc.output('[%s] Get. Except, non correct answrt!' % (PLUGIN_NAME))
        
        return http




class GUI(xbmcgui.WindowXMLDialog):

    def __init__(self, *args, **kwargs):
        xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
        self.val_status    = 0
        self.val_copy      = 0
        self.val_freespace = '[-]'
        self.val_log       = ''
        self.action_cancel_dialog = (1301, 10, 9, 7)
        self.setNum = kwargs['setNum']
        self.doModal()

    def onInit(self):
    	self.server_ip = __addon__.getSetting('server')
    	if (self.server_ip == None):
    	   self.server_ip = '127.0.0.1'
        self.AskServer()
        self.defineControls()
        self.showDialog()


    def AskServer(self):
        xbmc.log('[%s] AskServer' % (PLUGIN_NAME))
        res = Get('http://' + self.server_ip + '/cgi-bin/intrego-status.py')
#        res = Get('http://192.168.1.39:8000/cgi-bin/intrego-status.py')
        xbmc.log('[%s] AskServer. Get completed [%s]' % (PLUGIN_NAME, res))
        if None == res:
        	return None 
        try:
        	jsdata = json.loads(res)
        	xbmc.log('[%s] AskServer. jsdata = %s' % (PLUGIN_NAME, jsdata))
        	self.val_status     = jsdata['Status']
        	self.val_copy       = jsdata['CopyStatus']
        	self.val_freespace  = base64.b64decode(jsdata['FreeSpace'])
        	self.val_log        = base64.b64decode(jsdata['Log'])
        except :
        	xbmc.log('[%s] AskServer. GetData fail' % (PLUGIN_NAME))
        		
        xbmc.log('[%s] AskServer. GetData completed. Status[%s], CopyStatus[%s], FreeSpace[%s], Log[%s]' % (PLUGIN_NAME, self.val_status, self.val_copy, self.val_freespace, self.val_log))


    def defineControls(self):
        #actions
#        self.action_cancel_dialog = (1301, 10, 9, 7)
        #control ids
        self.control_status_id              = 1303
        self.control_ip_id                  = 1305
        self.control_copystatus_id          = 1307
        self.control_freespace_id           = 1309
        self.control_log_id                 = 1310
        self.control_progress_id            = 1320
        #controls
        self.ctrl_status     = self.getControl(self.control_status_id    )
        self.ctrl_ip         = self.getControl(self.control_ip_id        )
        self.ctrl_copystatus = self.getControl(self.control_copystatus_id)
        self.ctrl_freespace  = self.getControl(self.control_freespace_id )
        self.ctrl_log        = self.getControl(self.control_log_id       )
        self.ctrl_progress   = self.getControl(self.control_progress_id  )

    def showDialog(self):
        self.ctrl_status.setLabel    (getLS(10 + int(self.val_status)))		
        self.ctrl_ip.setLabel        (self.server_ip)		
        self.ctrl_copystatus.setLabel(getLS(20 + int(self.val_copy  )))		
        self.ctrl_freespace.setText  (self.val_freespace)		
        self.ctrl_log.setText        (self.val_log      )		
        self.ctrl_progress.setVisible(False             )		
        pass;

    def closeDialog(self):
        self.close()

    def onAction(self, action):
      	xbmc.log('[%s] OnAction. Action [%s]' % (PLUGIN_NAME, action.getId()))
        if action.getId() in self.action_cancel_dialog:
           self.closeDialog()
        pass

    def onFocus(self, controlId):
        pass

